import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {Circuit} from '../entity/circuit.model';
import {Observable} from 'rxjs/Observable';
import {AppConfig} from '../config';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class CircuitService {
  private readonly param = 'cirCuits';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }

  //请求线路列表
  getCircuitList(): Promise<Circuit[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as Circuit[])
      .catch(this.handleError);
  }

  //创建新线路
  create(circuits: Circuit): Promise<Circuit> {
    return this.http
      .post(this.url, JSON.stringify(circuits))
      .toPromise()
      .then(res => res.data)
      .catch(this.handleError);
  }

  //根据circuitName判断是否已经存在
  hasCircuitName(circuitName: string, circuitId: number, farmId: number): Observable<boolean> {
    if (circuitName === '')
      return Observable.of(true);

    circuitName = circuitName.replace(/#/, '%23')
    const url = `${this.url}/circuitName/${circuitName}/circuitId/${circuitId}/farmId/${farmId}`;
    //console.log(url);
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  //根据circuitCode判断是否已经存在
  hasCircuitCode(circuitCode: string, circuitId: number, farmId: number): Observable<boolean> {

    const url = `${this.url}/circuitCode/${circuitCode}/circuitId/${circuitId}/farmId/${farmId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  //编辑线路信息
  update(circuits: Circuit): Promise<Circuit> {
    const url = `${this.url}`;
    return this.http
      .put(url, JSON.stringify(circuits))
      .toPromise()
      .then(() => circuits)
      .catch(this.handleError);
  }

  //删除
  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  //批量线路删除
  batchDelete(keyIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${keyIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  //根据风场id查询线路；
  getCircuitByFarmId(id: number): Promise<Circuit[]> {
    const url = `${this.url}/farmId/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response => {
        return response.data as Circuit[]
      })
      .catch(this.handleError);
  }


  //根据工期id查询线路；
  getCircuitByPhaseId(id: number): Promise<Circuit[]> {
    const url = `${this.url}/phaseId/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.data as Circuit[])
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

}

